package controller

import (
	"cms/admin/request"
	"cms/core/config"
	"cms/core/response"
	"cms/dao"
	"cms/model"
	"cms/utils/convert"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
)

func GetBoardList(ctx *gin.Context)  {
	list := make([]model.Board, 0)
	if err := dao.GetBoardList(&list); err != nil {
		response.Error(ctx, err.Error())
		return
	}

	response.Success(ctx, gin.H{
		"list": list,
	})
}

// CreateBoard 新建栏目
func CreateBoard(ctx *gin.Context)  {
	var r request.BoardForm
	if err := ctx.ShouldBindJSON(&r); err != nil {
		response.Error(ctx, err.Error())
		return
	}
	data := &model.Board{}
	_ = copier.Copy(&data, &r)

	if err := dao.CreateBoard(data); err != nil {
		response.Error(ctx, err.Error())
		return
	}

	response.Success(ctx, data)
}

// EditBoard 修改单个栏目信息
func EditBoard(ctx *gin.Context)  {
	var r request.BoardForm
	if err := ctx.ShouldBindJSON(&r); err != nil {
		response.Error(ctx, err.Error())
		return
	}
	id := convert.StrToInt(ctx.Param("id"))

	data := &model.Board{}
	if err := dao.GetBoardInfo(id, data); err != nil {
		response.Error(ctx, err.Error())
		return
	}
	_ = copier.Copy(&data, &r)

	if err := dao.UpdateBoard(data); err != nil {
		response.Error(ctx, err.Error())
		return
	}

	response.Success(ctx, data)
}

// DeleteBoard 删除栏目
func DeleteBoard(ctx *gin.Context)  {
	id := convert.StrToInt(ctx.Param("id"))

	data := &model.Board{}
	if err := dao.GetBoardInfo(id, data); err != nil {
		response.Error(ctx, err.Error())
		return
	}

	if err := dao.DeleteBoard(data); err != nil {
		response.Error(ctx, err.Error())
		return
	}

	response.Success(ctx)
}

// GetBoardTypes 栏目类型列表 get admin/board_types
func GetBoardTypes(ctx *gin.Context)  {
	response.Success(ctx, gin.H{
		"list": config.Data.BoardTypes,
	})
}
